package com.kun.controller;

import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.kun.ai.common.DashScopeHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author kun.li
 */
@RestController
@RequestMapping("/ai")
@Slf4j
public class AiController {
    String tableProperties = """
             CREATE TABLE `test_test` (
              `xiaoshou_numer` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '销售量',
              `create_time` datetime DEFAULT NULL COMMENT '销售时间',
              `name` varchar(255) DEFAULT NULL COMMENT '销售人员'
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
            """;

    @Autowired
    private DashScopeHelper dashScopeHelper;


    @GetMapping
    public String helloAi() throws IOException {
        ClassPathResource classPathResource = new ClassPathResource("自然语言转sql.txt");
        String promptTemplate = classPathResource.getContentAsString(Charset.defaultCharset());
        String prompt = String.format(promptTemplate, "MYSQL5.7", tableProperties, "最近七天的销售量", "bar");
        log.info("prompt:{}", prompt);
        List<Message> messageList = new ArrayList<>();
        messageList.add(Message.builder().role(Role.USER.getValue()).content(prompt).build());
        String content = dashScopeHelper.getContent(messageList);
        log.info("content:{}", content);
        Pattern pattern = Pattern.compile("<SQL>(.*?)</SQL>");
        Matcher matcher = pattern.matcher(content.replaceAll("\\n", " "));
        if (matcher.find()) {
            return matcher.group(1);
        }
        return content;
    }
}
